import React, { useState, useRef, useEffect } from 'react'
import { message, Button, Card, Image, Modal, Input, Tooltip } from 'antd'
import ConfirmModal from '~/components/ConfirmModal'
import { toastManager } from '~/components/Toast'
import {
  UploadOutlined,
  // CopyOutlined,
  DeleteOutlined,
  EyeOutlined,
  LinkOutlined,
} from '@ant-design/icons'
import {
  getPictureListXhr,
  postDeletePictureXhr,
  postUploadPictureXhr,
} from '~/api/index'
import { UPLOAD_API } from '../../const'
import { hasPermission } from '~/utils/permission'

interface ImageItem {
  id: string
  filename: string
  url: string
  size: number
  format: string
  uploadTime: string
  width?: number
  height?: number
}

const PictureBed: React.FC = () => {
  const [imageList, setImageList] = useState<ImageItem[]>([])
  const [uploading, setUploading] = useState(false)
  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewImage, setPreviewImage] = useState('')
  const [previewTitle, setPreviewTitle] = useState('')
  const [searchText, setSearchText] = useState('')
  const [deleteModalVisible, setDeleteModalVisible] = useState(false)
  const [deleteLoading, setDeleteLoading] = useState(false)
  const [deleteFilename, setDeleteFilename] = useState('')
  const [deleteId, setDeleteId] = useState('')
  const fileInputRef = useRef<HTMLInputElement>(null)
  useEffect(() => {
    getPictureList()
  }, [])

  const getPictureList = async () => {
    try {
      const res = await getPictureListXhr()
      if (res?.code === 200 || res?.code === 0) {
        const list = (res.data || []).map((item: any) => {
          const fileSizeMb =
            typeof item?.file_size === 'string'
              ? parseFloat(item.file_size)
              : item?.file_size
          const sizeBytes = isNaN(fileSizeMb as number)
            ? 0
            : Math.round((fileSizeMb as number) * 1024 * 1024)

          return {
            id: String(
              item.id ?? item.file_name ?? item.original_name ?? Date.now()
            ),
            filename: item.original_name || item.file_name || '',
            url: item.url || item.local_path || '',
            size: sizeBytes,
            format: (item.file_type || item.file_format || '')
              ?.toString()
              .toLowerCase(),
            uploadTime:
              item.upload_time || item.created_at || new Date().toISOString(),
            width: item.width ?? undefined,
            height: item.height ?? undefined,
          } as ImageItem
        })

        setImageList(list)
      }
    } catch (error) {
      console.log('error', error)
    }
  }

  // 处理文件上传
  const handleUpload = async (file: File) => {
    if (!file) return false

    // 检查文件类型
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
      message.error('只能上传图片文件!')
      return false
    }

    // 检查文件大小 (100MB)
    const isLt100M = file.size / 1024 / 1024 < 100
    if (!isLt100M) {
      message.error('图片大小不能超过100MB!')
      return false
    }

    try {
      setUploading(true)

      // 创建FormData
      const formData = new FormData()
      formData.append('file', file)

      // 第一步：上传文件，拿到文件信息（路径、名称、大小）
      const uploadResp = await fetch(UPLOAD_API, {
        method: 'POST',
        body: formData,
      })
      const uploadResult = await uploadResp.json()

      if (uploadResult?.message !== '文件上传成功' || !uploadResult?.file) {
        toastManager.error(uploadResult?.message || '上传失败')
        setUploading(false)
        return false
      }

      const { filename, originalname, path, size } = uploadResult.file || {}

      // 第二步：保存数据库，提交必要字段
      const saveResp = await postUploadPictureXhr({
        fileName: filename,
        originalName: originalname,
        filePath: path,
        fileSize: size,
      })

      if (saveResp?.code === 200 || saveResp?.code === 0) {
        toastManager.success('上传成功!')
        setUploading(false)
        // 成功后直接刷新数据库列表
        await getPictureList()
      } else {
        toastManager.error(saveResp?.message || '保存失败')
        setUploading(false)
      }
    } catch (error) {
      toastManager.error('上传失败')
      setUploading(false)
    }

    return false // 阻止默认上传行为
  }

  // 处理拖拽上传
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    const files = Array.from(e.dataTransfer.files)
    if (files.length > 0) {
      handleUpload(files[0])
    }
  }

  // 处理粘贴上传
  const handlePaste = (e: React.ClipboardEvent) => {
    const items = e.clipboardData?.items
    if (items) {
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.startsWith('image/')) {
          const file = items[i].getAsFile()
          if (file) {
            handleUpload(file)
            break
          }
        }
      }
    }
  }

  // 复制链接
  const copyLink = async (url: string, type: 'url' | 'markdown' | 'html') => {
    let textToCopy = url

    if (type === 'markdown') {
      textToCopy = `![image](${url})`
    } else if (type === 'html') {
      textToCopy = `<img src="${url}" alt="image" />`
    }

    try {
      await navigator.clipboard.writeText(textToCopy)
      toastManager.success('链接已复制到剪贴板')
    } catch (error) {
      // 降级方案
      const textArea = document.createElement('textarea')
      textArea.value = textToCopy
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      toastManager.success('链接已复制到剪贴板')
    }
  }

  // 删除图片（使用ID）
  const handleDelete = async (id: string, filename: string) => {
    if (!hasPermission()) {
      toastManager.error('您没有权限删除图片,请联系博主')
      return
    }
    setDeleteId(id)
    setDeleteFilename(filename)
    setDeleteModalVisible(true)
  }

  // 确认删除
  const confirmDelete = async () => {
    setDeleteLoading(true)
    try {
      const res = await postDeletePictureXhr({ id: Number(deleteId) })
      if (res.code === 200 || res.code === 0) {
        toastManager.success('删除成功')
        // 先关闭弹窗，避免列表刷新异常导致弹窗不消失
        setDeleteModalVisible(false)
        try {
          await getPictureList()
        } catch (e) {
          // 忽略列表刷新失败
        }
      } else {
        toastManager.error(res.message || '删除失败')
      }
    } catch (error) {
      toastManager.error('删除失败')
    } finally {
      setDeleteLoading(false)
    }
  }

  // 取消删除
  const cancelDelete = () => {
    setDeleteModalVisible(false)
    setDeleteFilename('')
    setDeleteId('')
  }

  // 预览图片
  const handlePreview = (image: ImageItem) => {
    setPreviewImage(image.url)
    setPreviewTitle(image.filename)
    setPreviewVisible(true)
  }

  // 过滤图片列表
  const filteredImageList = imageList.filter((item) =>
    item.filename.toLowerCase().includes(searchText.toLowerCase())
  )

  // 格式化文件大小
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 标题和说明 */}
        <div className="mb-8 text-center">
          <h1 className="text-3xl font-bold text-gray-800 mb-4">图片上传</h1>
          <p className="text-gray-600 mb-2">
            复制图片，打开页面并按下 Ctrl+V 或 Command+V 就能自动上传啦~
          </p>
          <p className="text-sm text-gray-500">
            支持上传png、jpg、gif、webp等格式图片，最大支持100M，上传后支持复制url
          </p>
        </div>

        {/* 上传区域 */}
        <Card className="mb-6">
          <div
            className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-400 transition-colors"
            onDrop={handleDrop}
            onDragOver={(e) => e.preventDefault()}
            onPaste={handlePaste}
            tabIndex={0}
          >
            <UploadOutlined className="text-4xl text-gray-400 mb-4" />
            <p className="text-lg text-gray-600 mb-2">
              拖拽文件到此区域或点击上传
            </p>
            <p className="text-sm text-gray-500 mb-4">
              支持 JPG、PNG、GIF、WebP 等格式，最大 100MB
            </p>
            <Button
              type="primary"
              icon={<UploadOutlined />}
              loading={uploading}
              onClick={() => fileInputRef.current?.click()}
            >
              选择文件
            </Button>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              style={{ display: 'none' }}
              onChange={(e) => {
                const file = e.target.files?.[0]
                if (file) {
                  handleUpload(file)
                  e.target.value = '' // 清空input
                }
              }}
            />
          </div>
        </Card>

        {/* 搜索栏 */}
        <div className="mb-4 flex justify-between items-center">
          <Input.Search
            placeholder="搜索文件名"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 300 }}
          />
          <span className="text-gray-500">
            共 {filteredImageList.length} 张图片
          </span>
        </div>

        {/* 图片网格 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {filteredImageList.map((image) => (
            <Card
              key={image.id}
              hoverable
              className="overflow-hidden"
              actions={[
                <Tooltip title="复制链接">
                  <LinkOutlined onClick={() => copyLink(image.url, 'url')} />
                </Tooltip>,
                // <Tooltip title="复制Markdown">
                //   <CopyOutlined
                //     onClick={() => copyLink(image.url, 'markdown')}
                //   />
                // </Tooltip>,
                <Tooltip title="预览">
                  <EyeOutlined onClick={() => handlePreview(image)} />
                </Tooltip>,
                <Tooltip title="删除">
                  <DeleteOutlined
                    onClick={() =>
                      handleDelete(image?.id || '', image?.filename || '')
                    }
                    className="text-red-500"
                  />
                </Tooltip>,
              ]}
            >
              <div className="aspect-square overflow-hidden rounded">
                <Image
                  src={image.url}
                  alt={image.filename}
                  className="w-full h-full object-cover"
                  preview={false}
                />
              </div>
              <div className="mt-3">
                <p
                  className="text-sm font-medium text-gray-800 truncate"
                  title={image.filename}
                >
                  {image.filename}
                </p>
                <div className="text-xs text-gray-500 mt-1">
                  <p>格式: {image?.filename?.split('.')?.pop() || ''}</p>
                  <p>大小: {formatFileSize(image.size)}</p>
                  {image.width && image.height && (
                    <p>
                      尺寸: {image.width}×{image.height}
                    </p>
                  )}
                  <p>上传时间: {new Date(image.uploadTime).toLocaleString()}</p>
                </div>
              </div>
            </Card>
          ))}
        </div>

        {filteredImageList.length === 0 && (
          <div className="text-center py-12">
            <p className="text-gray-500">暂无图片</p>
          </div>
        )}
      </div>

      {/* 预览模态框 */}
      <Modal
        open={previewVisible}
        title={previewTitle}
        footer={null}
        onCancel={() => setPreviewVisible(false)}
        width="80%"
      >
        <Image
          alt={previewTitle}
          style={{ width: '100%' }}
          src={previewImage}
        />
      </Modal>

      {/* 删除确认弹窗 */}
      <ConfirmModal
        visible={deleteModalVisible}
        title="确认删除"
        content={`确定要删除图片 "${deleteFilename}" 吗？删除后无法恢复。`}
        confirmText="确认删除"
        cancelText="取消"
        loading={deleteLoading}
        onConfirm={confirmDelete}
        onCancel={cancelDelete}
      />
    </div>
  )
}

export default PictureBed
